//
//  KRReadListController.m
//  cookBook
//
//  Created by kuroken on 16/1/12.
//  Copyright © 2016年 kuroken. All rights reserved.
//

#import "KRReadListController.h"
#import "KRConst.h"
#import "KRReadListCell.h"
#import "KRReadList.h"
#import "KRHttpRecipeTool.h"
#import <MJExtension.h>
#import <SVProgressHUD.h>
#import <MJRefresh.h>
#import "KRReadPostController.h"
#import "KRShareWebviewController.h"
#import "KRNoNetCell.h"
#import "KRWebController.h"

@interface KRReadListController ()
@property (nonatomic, assign) NSUInteger offset;
/** 当前请求 */
@property (nonatomic, weak) NSURLSessionDataTask *currentDataTask;
@property (nonatomic, assign, getter=isError) BOOL error;
@end

@implementation KRReadListController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.scrollEnabled = NO;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    if (self.isPush) { // 是push进来的
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;

        // 下拉刷新控件
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
        
        // 上拉刷新控件
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
        // 请求数据
        [self loadData];
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!self.readList && self.isPush) {
        // 显示指示器
        [SVProgressHUD show];
        self.tableView.userInteractionEnabled = NO;
        self.tableView.scrollEnabled = NO;
    }
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.currentDataTask cancel];
    self.currentDataTask = nil;
    [SVProgressHUD dismiss];
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }

}

- (void)dealloc
{
    NSLog(@"%s", __func__);
}

/**
 *  加载更多数据
 */
- (void)loadMoreData
{
    KRLog(@"从第%d条阅读开始加载", (int)self.offset);
    
    if (_currentDataTask) {
        [self.currentDataTask cancel];
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }
    }
    self.currentDataTask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRReadGetList;
        requestParams[@"offset"] = [NSString stringWithFormat:@"%d", (int)self.offset];

    } success:^(NSURLSessionDataTask *task, id json) {
        if (self.currentDataTask != task) return;
        
        self.offset += 10;
        NSArray *newReadList = [KRReadList mj_objectArrayWithKeyValuesArray:json[@"result"][@"list"]];
        if (newReadList.count == 0) {
            [SVProgressHUD showInfoWithStatus:@"已无更多数据"];
        }
        [self.readList addObjectsFromArray:newReadList];
        [self.tableView reloadData];
        
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }

    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.currentDataTask != task) return;
        
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"网络繁忙！"];
        });
        
        KRLog(@"%@, %@", self, error);
    }];
}

/**
 *  加载数据
 */
- (void)loadData
{
    if (_currentDataTask) {
        [self.currentDataTask cancel];
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    }

    self.currentDataTask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRReadGetList;
        requestParams[@"offset"] = @"0";
    } success:^(NSURLSessionDataTask *task, id json) {
        if (self.currentDataTask != task) return;
        
        if (!self.readList) {
            self.error = NO;
            self.tableView.scrollEnabled = YES;
        }

        self.offset = 0;
        self.readList = [KRReadList mj_objectArrayWithKeyValuesArray:json[@"result"][@"list"]];
        self.offset += self.readList.count;
        
        [self.tableView reloadData];
        
        // 移除指示器
        [SVProgressHUD dismiss];
        self.tableView.userInteractionEnabled = YES;

        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
            [SVProgressHUD showSuccessWithStatus:@"当前已是最新数据"];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.currentDataTask != task) return;
        if (!self.readList) {
            self.error = YES;
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
            self.tableView.userInteractionEnabled = YES;
        }
        
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"网络繁忙！"];
        });
        
        KRLog(@"%@, %@", self, error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isError) return 1; // 请求失败
    return self.readList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isError) {
        KRNoNetCell *cell = [KRNoNetCell cellWithTableView:tableView];
        [cell setNoNetHint:@"请求超时"];
        return cell;
    }

    KRReadListCell *cell = [KRReadListCell cellWithTableView:tableView];
    cell.readList = self.readList[indexPath.row];
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.isPush) return baseCellHeight;
    if (self.isError) return [UIScreen mainScreen].bounds.size.height - KRTopBarHeight;

    return baseCellHeight + cellPadding * 2; // 上下各加10的间距
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isError) {
        self.error = NO;
        [self.tableView reloadData];
        [self loadData];
        return;
    }
    
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];// 取消选中
    
    NSString *topicID = self.readList[indexPath.row].topicID;
    NSString *shareID = self.readList[indexPath.row].shareID;

    if (topicID) {
        KRReadPostController *readPostVc = [[KRReadPostController alloc] init];
        readPostVc.topicID = topicID;
        [self.navigationController pushViewController:readPostVc animated:YES];
    } else if (shareID) {
        KRShareWebviewController *shareWebviewVc = [[KRShareWebviewController alloc] init];
        shareWebviewVc.shareID = shareID;
        [self.navigationController pushViewController:shareWebviewVc animated:YES];
    } else {
        KRWebController *webVc = [[KRWebController alloc] init];
        webVc.url = self.readList[indexPath.row].url;
        [self.navigationController pushViewController:webVc animated:YES];
    }
}

@end